import * as types from '../mutation-types'
import http from '@/utils/http'
import { INTEGRAL_EXCHANGE_RATIO } from '@/config'
export default {
  state: {
    // 购物车数据
    list: [],
    // 直接购买，商品信息
    buyNowList: [],
    // 操作类型
    action: 'add_cart',
    checkedCoupon: null,
    teamFoundId: 0
  },
  getters: {
    cartCount: (state, getters) => {
      return state.list.length
    },
    initCartList: (state, getters) => {
      let list = []
      if (state.action === 'add_cart') {
        list = state.list
      } else {
        list = state.buyNowList
      }
      return list.filter((item) => {
        return getters.initItem(item)
      })
    },
    initItem: (state, getters) => (item) => {
      let price = 0
      let fDiscount = 0
      let tDiscount = 0
      let stock = item.goods.stock
      // 限时秒杀
      if (item.goods.underway_flash_sale && state.action !== 'team_activity') {
        fDiscount = item.goods.underway_flash_sale.discount
      }
      // 拼团
      if (item.goods.underway_team_activity && state.action === 'team_activity') {
        tDiscount = item.goods.underway_team_activity.discount
      }
      // 规格价
      if (item.spec) {
        price = item.spec.price
        stock = item.spec.stock
      } else {
        price = item.goods.price
      }
      price = (price * 100 - fDiscount * 100) / 100
      price = (price * 100 - tDiscount * 100) / 100
      if (price < 0) {
        price = 0
      }
      item.price = price
      item.stock = stock
      return item
    },
    cartChecked: (state, getters) => {
      return getters.initCartList.filter((item) => {
        if (item.checked) {
          return item
        }
      })
    },
    cartCheckedNumber: (state, getters) => {
      return getters.cartChecked.reduce((total, item) => {
        total += item.quantity
        return total
      }, 0)
    },
    cartCheckedTotalPrice: (state, getters) => {
      return getters.cartChecked.reduce((total, item) => {
        total += item.price * item.quantity
        return total
      }, 0)
    },
    cartCheckedFullCut: (state, getters) => {
      let fullCut = 0
      getters.cartChecked.forEach((item) => {
        if (item.goods.full_cut) {
          let tempPrice = item.price * item.quantity
          item.goods.full_cut.some((f) => {
            if (tempPrice >= f.amount) {
              fullCut -= parseFloat(f.price)
              return true
            }
          })
        }
      })
      return fullCut
    },
    availableIntegralNumber: (state, getters) => {
      let goodsIntegeral = getters.cartChecked.reduce((total, item) => {
        total += item.goods.exchange_integral
        return total
      }, 0)
      let userIntegral = getters.userInfo ? getters.userInfo.integral : 0
      return (goodsIntegeral > userIntegral) ? userIntegral : goodsIntegeral
    },
    availableIntegralPrice: (state, getters) => {
      return 0 - getters.availableIntegralNumber * INTEGRAL_EXCHANGE_RATIO
    },
    cartCheckedShippingFee: (state, getters) => {
      return 0
    },
    cartCheckedCouponPrice: (state, getters) => {
      let price = 0
      if (state.checkedCoupon) {
        price = 0 - state.checkedCoupon.money
      }
      return price
    },
    cartCheckedCoupon: (state, getters) => {
      return state.checkedCoupon
    },
    cartCheckedPayTotal: (state, getters) => (userIntegral) => {
      let discount = getters.userInfo && getters.userInfo.level.discount > 0 ? getters.userInfo.level.discount : 1
      discount = discount * 100
      let price = getters.cartCheckedTotalPrice * discount / 100 +
      getters.cartCheckedFullCut +
      getters.cartCheckedShippingFee +
      getters.cartCheckedCouponPrice
      if (userIntegral) {
        price = price + getters.availableIntegralPrice
      }
      if (price < 0) {
        price = 0
      }
      return price
    }
  },
  mutations: {
    [types.SET_CART_LIST]: (state, list) => {
      state.list = list
    },
    [types.SET_TEAM_FOUND_ID]: (state, id) => {
      state.teamFoundId = id
    },
    [types.DELETE_CART]: (state, index) => {
      state.list.splice(index, 1)
    },
    [types.CHECK_ALL_CART]: (state, checked) => {
      if (state.list !== null) {
        state.list.forEach((item) => {
          item.checked = checked
        })
      }
    },
    [types.SET_CART_LOAD_STATUS]: (state, status) => {
      state.loaded = status
    },
    [types.SET_BUY_NOW_LIST]: (state, data) => {
      let list = []
      list.push(data)
      state.buyNowList = list
    },
    [types.SET_ACTION_TYPE]: (state, type) => {
      state.action = type
    },
    [types.SET_CHECKED_COUPON]: (state, coupon) => {
      state.checkedCoupon = coupon
    }
  },
  actions: {
    getCartList: ({commit}) => {
      return new Promise((resolve, reject) => {
        http.get('/carts').then((response) => {
          commit(types.SET_CART_LIST, response.data)
          commit(types.SET_CART_LOAD_STATUS, true)
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    addToCart: ({dispatch}, product) => {
      return new Promise((resolve, reject) => {
        http.post('/carts', product).then((response) => {
          dispatch('getCartList')
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    deleteCart: ({commit, state}, index) => {
      return new Promise((resolve, reject) => {
        http.delete('/carts/' + state.list[index].id).then((response) => {
          commit(types.DELETE_CART, index)
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    updateCart: ({commit}, data) => {
      return new Promise((resolve, reject) => {
        http.put('/carts/' + data.id, data).then((response) => {
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    }
  }
}
